import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-09-29
 * Time: 14:46
 */
class Solution14 {
    int m, n;
    int[] dx = {1,-1,0,0};
    int[] dy = {0,0,-1,1};
    public int cutOffTree(List<List<Integer>> forest) {
        m = forest.size(); n =forest.get(0).size();
        // 1.排序准备工作
        List<int[]> trees = new ArrayList<>();
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(forest.get(i).get(j) > 1) {
                    trees.add(new int[]{i,j});
                }
            }
        }
        Collections.sort(trees,(a, b)->{
            return forest.get(a[0]).get(a[1])-forest.get(b[0]).get(b[1]);
        });

        // 2.按照顺序砍树
        int ret = 0;
        int bx = 0, by = 0;
        for(int[] tree : trees) {
            int x = tree[0], y = tree[1];
            int step = bfs(forest,bx,by,x,y);
            if(step == -1) {
                return -1;
            }
            ret += step;
            bx = x;
            by = y;
        }
        return ret;
    }

    public int bfs(List<List<Integer>> f,int bx,int by,int ex,int ey) {
        if(bx == ex && by == ey) {
            return 0;
        }
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[]{bx,by});
        boolean[][] vis = new boolean[m][n];
        vis[bx][by] = true;
        int step = 0;
        while(!q.isEmpty()) {
            int size = q.size();
            step++;
            while(size-- != 0) {
                int[] t = q.poll();
                int a = t[0],b = t[1];
                for(int k = 0; k < 4; k++) {
                    int x = a+dx[k],y = b+dy[k];
                    if(x >= 0 && x < m && y >= 0 && y < n && f.get(x).get(y) != 0 && !vis[x][y]) {
                        if(x == ex && y == ey) {
                            return step;
                        }
                        q.add(new int[]{x,y});
                        vis[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }
}
